package jdbc.pool.utils;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DbUtils_DBCP {

    //1创建连接池对象
    private static BasicDataSource dataSource;

    static {

        //Properties 属性集合  (1)没有泛型   （2）存储字符串类型  （3）和流有关
        Properties properties = new Properties();
        //使用类加载器的方式获取流
        InputStream is = DbUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");
        try {
            properties.load(is);
            //初始化连接池
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池失败");
        }

    }


    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeAll(Connection conn, Statement stat, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stat != null) {
                stat.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static int executeUpdate(String sql, Object... params) {
        //1获取连接
        Connection conn = null;
        PreparedStatement pstat = null;
        try {
            conn = getConnection();
            assert conn != null;
            pstat = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstat.setObject(i + 1, params[i]);
                }
            }
            return pstat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, pstat, null);
        }
        return -1;
    }
}
